package eu.webhib.frmwrk.jsf.utils;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

/**
 * Basic message helper functions
 */
public class MsgUtil {

   private static final Logger log = Logger.getLogger(MsgUtil.class);

   /**
    * Get text for given key and indicates an error if key is not found
    * @param msgKey key of message loaded from resource bundle
    * @return text loaded from resource bundle
    */
   public static String getMessageText(String msgKey) {
      FacesContext ctx = FacesContext.getCurrentInstance();
      Locale loc = ctx.getViewRoot().getLocale();
      ResourceBundle bundle = ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(), loc);
      try {
         return bundle.getString(msgKey);
      } catch (Exception ex) {
         log.error("could not find message key '" + msgKey + "'");
         return msgKey;
      }
   }

   /**
    * Get text for given key if key exists, otherwise return null
    * @param msgKey key of message loaded from resource bundle
    * @return text loaded from resource bundle or null if not found
    */
   public static String getMessageTextIfExists(String msgKey) {
      FacesContext ctx = FacesContext.getCurrentInstance();
      Locale loc = ctx.getViewRoot().getLocale();
      ResourceBundle bundle = ResourceBundle.getBundle(ctx.getApplication().getMessageBundle(), loc);
      try {
         return bundle.getString(msgKey);
      } catch (Exception ex) {
         return null;
      }
   }

   /**
    * Get text for given key and performs parameter substitution
    * @param msgKey key of message loaded from resource bundle
    * @param args arguments used for parameter substitution in retrieved message text
    * @return found and substituted message text
    */
   public static String getMessageText(String msgKey, Object... args) {
      String msg = getMessageText(msgKey);
      /** because of method overload: */
      assert (args != null);
      /** parameter substitution */
      MessageFormat format = new MessageFormat(msg);
      return format.format(args);
   }

   /**
    * Creates Faces message with given severity and parameters
    * @param severity severity of message to be created
    * @param msgKey key of message loaded from resource bundle
    * @param args arguments used for parameter substitution in retrieved message text
    * @return created Faces message
    */
   public static FacesMessage createFacesMessage(FacesMessage.Severity severity, String msgKey, Object... args) {
      String msg = getMessageText(msgKey, args);
      return new FacesMessage(severity, msg, msg);
   }

   /**
    * Creates Faces message for given exception
    * @param msgKey key of message loaded from resource bundle
    * @param args arguments used for parameter substitution in retrieved message text
    * @param ex exception those message and cause is used for the message text
    * @return created Faces message
    */
   public static FacesMessage createErrorMessage(String msgKey, Exception ex) {
      String msg = getMessageText(msgKey);
      String exMsg = ex.getLocalizedMessage();
      if (exMsg != null && exMsg.length() > 0) {
         msg += ": " + exMsg;
      }
      String causeText = ex.getCause().toString();
      if (causeText != null && causeText.length() > 0) {
         msg += ": " + causeText;
      }
      return new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
   }
   /*
   public static void addInfoMessage(String msgKey, Object... args) {
   FacesContext.getCurrentInstance().addMessage(null, createFacesMessage(FacesMessage.SEVERITY_INFO, msgKey, args));
   }

   public static void addErrorMessage(String msgKey, Object... args) {
   FacesContext.getCurrentInstance().addMessage(null, createFacesMessage(FacesMessage.SEVERITY_ERROR, msgKey, args));
   }

   public static void addErrorMessage(String msgKey, Exception ex) {
   FacesContext.getCurrentInstance().addMessage(null, createErrorMessage(msgKey, ex));
   }


   public static void addFieldError(String fieldId, String msgKey, Object... args) {
   // set flag
   FacesContext.getCurrentInstance().validationFailed();
   // fieldId: the id of the input-tag, if
   // <h:form id="register-form">
   //   <h:inputText id="email"
   //   -> fieldId = "register-form:email"
   // <h:form id="register-form" prependId="false">
   //   <h:inputText id="email"
   //   -> fieldId = "email"
   // When using composite components, the composite component carries the given fieldId
   // and the input-tag is a children with the id="input", so the fieldId = "email:input"
   FacesContext.getCurrentInstance().addMessage(fieldId + inputChildId,
   createFacesMessage(FacesMessage.SEVERITY_ERROR, msgKey, args));
   }

   /**
    * Adds an error message to the given field component and uses the field name for the first
    * parameter of the message test substitution
    * @param fieldId name (JSF id) of the field
    * @param msgKey the message key
    * @param args the other arguments used for the message text substitution
    *
   public static void addFieldErrorFieldName(String fieldId, String msgKey, Object... args) {
   Object msgArgs[] = new Object[args.length + 1];
   msgArgs[0] = getMessageText("field_" + fieldId);
   int i = 1;
   for (Object o : args) {
   msgArgs[i++] = o;
   }
   FacesContext.getCurrentInstance().validationFailed();
   FacesContext.getCurrentInstance().addMessage(fieldId + inputChildId,
   createFacesMessage(FacesMessage.SEVERITY_ERROR, msgKey, msgArgs));
   }

   public static boolean isInputOk() {
   return !FacesContext.getCurrentInstance().isValidationFailed();
   }
    */
}
